<template>
  <div class="choose">
    <div class="choo-nav">
      <t-navbar
        title="自选大厅"
        :fixed="false"
        left-arrow
        @left-click="handleClick"
      />
    </div>
    <!-- 内容 -->
    <div class="fl">
      <div class="search-bar">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="搜索花材/供应商"
        />
        <button class="search-button">搜索</button>
      </div>
      <div class="shop-container">
        <div class="sidebar">
          <button
            v-for="category in categories"
            :key="category"
            :class="[
              'sidebar-button',
              { active: selectedCategory === category },
            ]"
            @click="selectCategory(category)"
          >
            {{ category }}
          </button>
        </div>

        <div class="main-content">
          <div class="sort_box_right_top">
            <div
              class="sort_box_right_top1"
              v-for="filter in filters"
              :key="filter"
            >
              <div class="sort_box_right_top11">{{ filter }}</div>
              <div class="sort_box_right_top12">
                <div class="right_img" @click="sortBy(filter, 'asc')">
                  <img :src="currentSortImage(filter, 'asc')" alt="升序" />
                </div>
                <div class="right_img" @click="sortBy(filter, 'desc')">
                  <img :src="currentSortImage(filter, 'desc')" alt="降序" />
                </div>
              </div>
            </div>
          </div>

          <div class="product-list">
            <div
              v-for="product in filteredProducts"
              :key="product.name"
              class="product-card"
            >
              <img :src="product.img" alt="product" class="product-image" />
              <div class="product-info" @click="list(product.id)">
                <div class="product-name">
                  <div class="product-title">{{ product.name }}</div>
                  <div class="product-tag">{{ product.size }}</div>
                </div>
                <div class="product-brand">
                  <div class="product-brand-name">{{ product.brand }}</div>
                  <div class="product-brand-level">供应充足</div>
                </div>
                <div class="product-price">
                  <span v-if="product.quantity === 0 || product.quantity === 1">
                    ￥{{ product.price }}
                    <!-- 显示原始价格 -->
                  </span>
                  <span v-else>
                    ￥{{ (product.price * product.quantity).toFixed(2) }}
                    <!-- 显示总价 -->
                  </span>
                  <span v-if="product.oldPrice" class="old-price">{{
                    product.oldPrice
                  }}</span>
                </div>
              </div>
              <div class="product-actions">
                <button
                  @click="decreaseQuantity(product)"
                  v-if="product.quantity > 0"
                >
                  -
                </button>
                <div class="quantity" v-if="product.quantity > 0">
                  {{ product.quantity }}
                </div>
                <button @click="increaseQuantity(product)">+</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <div class="flower-display">
      <div class="image-gallery">
        <div class="imgg">
          <img
            v-for="(image, index) in images"
            :key="index"
            :src="image"
            alt="flower"
            class="flower-image"
          />
        </div>
        <div class="tui">推荐方案</div>
      </div>
      <div class="footer">
        <div class="total">
          合计: <span class="price">¥{{ totalPrice }}</span>
        </div>
        <button class="checkout-button" @click="checkout">结算</button>
      </div>
    </div>
  </div>
</template>
<script setup>
import "./choo.css";
import { ref, computed,onMounted } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const categories = ref([
  "推荐",
  "玫瑰",
  "康乃馨",
  "百合",
  "菊花",
  "绣球花",
  "洋桔梗",
  "草花",
  "配花",
  "配叶",
  "包装",
]);
const selectedCategory = ref("推荐");
const filters = ref(["价格", "等级", "销量", "选颜色"]);
const searchQuery = ref(""); // 新增搜索查询变量
const sortByFilter = ref(""); // 新增排序变量
const currentSorts = ref({}); // 用于存储当前排序状态
const sortOrder = ref("asc"); // 新增排序顺序变量
const products = ref([
  {
    id: 1,
    name: "玫瑰",
    size: "55CM",
    brand: "品牌玫瑰",
    price: "18.7",
    img: "https://picsum.photos/200/300?1",
    quantity: 0,
    category: "玫瑰",
  },
  {
    id: 2,
    name: "向日葵",
    size: "55CM",
    brand: "品牌向日葵",
    price: "18.7",
    oldPrice: "¥19.2",
    img: "https://picsum.photos/200/300?2",
    quantity: 0,
    category: "向日葵",
  },
  {
    id: 3,
    name: "夜莺",
    size: "55CM",
    brand: "品牌夜莺",
    price: "30.7",
    img: "https://picsum.photos/200/300?3",
    quantity: 0,
    category: "夜莺",
  },
  {
    id: 4,
    name: "康乃馨",
    size: "55CM",
    brand: "品牌夜莺",
    price: "25.7",
    img: "https://picsum.photos/200/300?4",
    quantity: 0,
    category: "康乃馨",
  },
  {
    id: 5,
    name: "百合",
    size: "55CM",
    brand: "品牌百合",
    price: "26.7",
    img: "https://picsum.photos/200/300?5",
    quantity: 0,
    category: "百合",
  },
  {
    id: 6,
    name: "菊花",
    size: "55CM",
    brand: "品牌夜莺",
    price: "15.7",
    img: "https://picsum.photos/200/300?6",
    quantity: 0,
    category: "菊花",
  },
  {
    id: 7,
    name: "绣球花",
    size: "55CM",
    brand: "品牌夜莺",
    price: "10.7",
    img: "https://picsum.photos/200/300?7",
    quantity: 0,
    category: "绣球花",
  },
  {
    id: 8,
    name: "洋桔梗",
    size: "55CM",
    brand: "品牌夜莺",
    price: "40",
    img: "https://picsum.photos/200/300?8",
    quantity: 0,
    category: "洋桔梗",
  },
  {
    id: 9,
    name: "草花",
    size: "55CM",
    brand: "品牌夜莺",
    price: "30",
    img: "https://picsum.photos/200/300?9",
    quantity: 0,
    category: "草花",
  },
  // 添加更多产品...
]);
const totalPrice = computed(() => {
  return products.value
    .reduce((total, product) => {
      return total + product.price * product.quantity;
    }, 0)
    .toFixed(2);
});
const images = ref([]);
const checkout = () => {
  const orderItems = products.value
    .filter((product) => product.quantity > 0)
    .map((product) => ({
      name: product.name,
      price: product.price,
      totalPrice: (product.price * product.quantity).toFixed(2),
      img: product.img,
      quantity: product.quantity,
    }));

  router.push({
    path: "/order",
    query: {
      images: JSON.stringify(images.value),
      items: JSON.stringify(orderItems),
    },
  });
};

const list = (id) => {
  // 根据传入的 id 查找对应的商品
  const product = products.value.find((product) => product.id === id);

  // 找到了对应商品，打印信息
  if (product) {
    console.log(`商品名称: ${product.name}`);
    console.log(`商品数量: ${product.quantity}`);
    console.log(`商品价格: ${product.price}`);
    console.log(`商品图片: ${product.img}`);

    // 将该商品信息传递到新的页面
    const orderItem = {
      name: product.name,
      quantity: product.quantity,
      price: product.price,
      totalPrice: (product.price * product.quantity).toFixed(2),
      img: product.img,
    };

    router.push({
      path: "/comm", // 这里为目标路径
      query: {
        images: JSON.stringify(images.value),
        item: JSON.stringify(orderItem), // 传递单个商品信息
      },
    });
  } else {
    console.log("未找到对应商品");
  }
};

const selectCategory = (category) => {
  selectedCategory.value = category;
};

const sortBy = (filter, order) => {
  currentSorts.value[filter] = order; // 设置当前排序
  sortByFilter.value = filter; // 设置当前过滤器
  sortOrder.value = order; // 更新排序方向
  console.log(`排序：${filter} - ${order}`);
};
const currentSortImage = (filter, order) => {
  // 这里根据当前的排序状态返回对应的图片
  if (currentSorts.value[filter] === order) {
    return order === "asc"
      ? "/public/image/升序.png"
      : "/public/image/降序.png"; // 激活状态下照片
  }
  return order === "asc"
    ? "/public/image/升序 (1).png"
    : "/public/image/降序 (1).png"; // 默认图片
};
const filteredProducts = computed(() => {
  let filtered = products.value.filter(
    (product) =>
      (product.category === selectedCategory.value ||
        selectedCategory.value === "推荐") &&
      (product.name.includes(searchQuery.value) ||
        product.brand.includes(searchQuery.value))
  );

  // 按照价格进行排序
  if (sortByFilter.value === "价格") {
    filtered.sort((a, b) => {
      const totalA = parseFloat(a.price);
      const totalB = parseFloat(b.price);
      return sortOrder.value === "asc" ? totalA - totalB : totalB - totalA; // 升序或降序
    });
  }

  return filtered;
});
const increaseQuantity = (product) => {
  product.quantity++;
  if (product.quantity === 1) {
    images.value.push(product.img);
  }
};
const decreaseQuantity = (product) => {
  product.quantity--;
  if (product.quantity === 0) {
    images.value.splice(images.value.indexOf(product.img), 1);
  }

};
const handleClick = () => {
  console.log("left-click");
  window.history.go(-1);
};
</script>
<style lang="scss" scoped></style>
